package com.glory.dmegcpda.viewmodel

import android.content.Context
import android.graphics.BitmapFactory
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.databinding.ObservableArrayList
import com.glory.dmegcpda.BR
import com.glory.dmegcpda.R
import com.glory.dmegcpda.bean.PdfBean
import com.glory.dmegcpda.utils.PdfItextUtil
import com.glory.dmegcpda.utils.PdfUtils
import com.glory.mvvmnet.base.BaseViewModel
import com.glory.mvvmnet.entity.CallObserveBean
import com.glory.mvvmnet.entity.ToastMessageBean
import com.itextpdf.text.PageSize
import me.tatarka.bindingcollectionadapter2.ItemBinding
import java.io.File
import java.io.FileInputStream
import java.text.SimpleDateFormat
import java.util.*

class PatrilModel : BaseViewModel() {

    var stepList = arrayListOf(
        "准备间",
        "划片室",
        "串焊",
        "上玻",
        "排版",
        "叠焊",
        "贴条码",
        "上EVA",
        "前EL",
        "层压",
        "翻转检验",
        "装框",
        "接线盒/灌胶",
        "接线盒检验",
        "固化",
        "IV",
        "绝缘/耐压测试",
        "后EL",
        "铭牌",
        "终检",
        "分档",
        "包装"
    )

    var mPdfBeanList = arrayListOf<PdfBean>()

    var iconList = ObservableArrayList<String>()
    var iconBinding = ItemBinding.of<String>(BR.iconItem, R.layout.item_icon)


    fun tempSave(step: String, desc: String) {
        val pdfBean = PdfBean()
        pdfBean.title = step
        pdfBean.text = desc
        var mList = arrayListOf<String>()
        mList.addAll(iconList)
        pdfBean.imageUrl = mList
        mPdfBeanList.add(pdfBean)
        iconList.clear()
        defUI.toastEvent.value = ToastMessageBean("临时保存成功", true)
        defUI.callObserve.value = CallObserveBean(100, "temp")
    }

    private val handler = Handler(Looper.getMainLooper())
    fun save(context: Context,step: String, desc: String) {

        val pdfBean = PdfBean()
        pdfBean.title = step
        pdfBean.text = desc
        var mList = arrayListOf<String>()
        mList.addAll(iconList)
        pdfBean.imageUrl = mList
        mPdfBeanList.add(pdfBean)

        val file = File(PdfUtils.ADDRESS)
        if (!file.exists()) {
            file.mkdirs()
        }
        val time = System.currentTimeMillis()
        val date = Date(time)
        val sdf = SimpleDateFormat("yyyyMMdd_HHmmss")
        val pdf_address: String = TestFilePathApkPrivate(
            context,
            Environment.getExternalStorageDirectory().absolutePath + File.separator
        ) + "/DMEGC_" + sdf.format(date) + ".pdf"

        Log.e("保存路径", pdf_address)
        Thread {
            val pdfItextUtil = PdfItextUtil(pdf_address)
            try {

                mPdfBeanList.forEach { it ->
                    pdfItextUtil.addTitleToPdf(it.title)
                    pdfItextUtil.addTextToPdf(it.text)
                    it.imageUrl.forEach { str ->
                        val bitmap =
                            BitmapFactory.decodeStream(FileInputStream(str))
                        pdfItextUtil.addImageToPdfCenterH(
                            str,
                            400.0f,
                            600.0f
                        )
                    }
                }
                handler.post{
                    defUI.callObserve.value = CallObserveBean(200,"save")
                }


            } catch (e: Exception) {
                e.printStackTrace()
                Log.e("TAG", "save: " + e.message)
                handler.post{
                    defUI.callObserve.value = CallObserveBean(404,e.message.toString())
                }
            } finally {
                pdfItextUtil.close()
            }
        }.start()
    }

    private fun TestFilePathApkPrivate(context: Context, FileDirName: String): String? {
        //不需要挂载测试，因为 app 都可以装 为什么 会没有数据
        val filedirpath = context.getExternalFilesDir(FileDirName)!!.path //文件夹
        val fileDir = File(filedirpath) //创建文件夹
        if (fileDir.exists()) {    //判断文件是否存在  很重要  别每次都会去覆盖数据
            fileDir.setWritable(true)
        } else {
            try {
                fileDir.mkdir()
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
                Log.i("LOG_Error", "文件夹创建错误   TestFilePathExternalData()" + e.message)
            }
        }
        return filedirpath
    }

}